package cn.uniquesoft.util;

import java.util.ArrayList;
import java.util.List;

import cn.uniquesoft.vo.MenuTreeVO;
import cn.uniquesoft.vo.MenuVO;

/**
 * @创建人 zyx
 * @创建时间 2017年6月22日 下午2:38:29
 * @描述 菜单辅助类
 */
public class MenuUtil {

	public static String getJson(List<MenuVO> list) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("[");
		iterGet(list, 0, buffer);
		buffer.append("]");
		String tmp = buffer.toString();
		tmp = tmp.replaceAll(",\n]", "\n]");
		return tmp;
	}

	private static void iterGet(List<MenuVO> list, int pid, StringBuffer buffer) {
		for (MenuVO node : list) {
			// 查找所有父节点为pid的所有对象，然后拼接为json格式的数据
			if (pid == node.getIpid()) {
				buffer.append("{\"iid\":\"" + node.getIid() + "\",\"ipid\":\"" + node.getIpid() + "\",\"cname\":\"" + node.getCname() + "\",\"cicon\":\"icon-" + node.getCicon() + "\",\"curl\":\"" + node.getCurl() + "\",\"children\":[");
				// 递归
				iterGet(list, node.getIid(), buffer);
				buffer.append("]},\n");
			}
		}
	}

	public static List<MenuTreeVO> getMenuTreeList(List<MenuVO> list) {
		List<MenuTreeVO> menuTreeList = new ArrayList<MenuTreeVO>();

		for (MenuVO menuVO : list) {
			if (menuVO.getIpid() == -1) {
				MenuTreeVO menuTree = getMenuTreeVO(menuVO);
				menuTreeList.add(menuTree);
			}
		}

		for (MenuTreeVO menuTree : menuTreeList) {
			for (MenuVO menuVO : list) {
				if (menuVO.getIpid() != -1 && menuTree.getIid() == menuVO.getIpid()) {
					MenuTreeVO childMenu = getMenuTreeVO(menuVO);
					menuTree.addChildItem(childMenu);
				}
			}
		}

		return menuTreeList;
	}

	private static MenuTreeVO getMenuTreeVO(MenuVO menuVO) {
		MenuTreeVO menuTreeVO = new MenuTreeVO();
		menuTreeVO.setId(menuVO.getIid());
		menuTreeVO.setText(menuVO.getCname());
		menuTreeVO.setIconCls(menuVO.getCicon());
		menuTreeVO.setIid(menuVO.getIid());
		menuTreeVO.setIpid(menuVO.getIpid());
		menuTreeVO.setCname(menuVO.getCname());
		menuTreeVO.setIcreator(menuVO.getIcreator());
		menuTreeVO.setCcreator(menuVO.getCcreator());
		menuTreeVO.setDcreator(menuVO.getDcreator());
		menuTreeVO.setImodify(menuVO.getImodify());
		menuTreeVO.setCmodify(menuVO.getCmodify());
		menuTreeVO.setDmodify(menuVO.getDmodify());
		menuTreeVO.setCurl(menuVO.getCurl());
		menuTreeVO.setIsort(menuVO.getIsort());
		menuTreeVO.setIshow(menuVO.getIshow());
		menuTreeVO.setCparam(menuVO.getCparam());
		return menuTreeVO;
	}
}
